const express = require('express')
const router = express.Router()
const Mentorship = require('../models/Mentorship')
const { markFileAsReferenced, unmarkFileReference } = require('../middlewares/fileReference')
const authMiddleware = require('../middlewares/auth')
// 创建新班级
router.post('/addClasses', authMiddleware(), async (req, res) => {
  try {
    const { startDate, fileId, className, description, isSuccessCase } = req.body

    const newClass = new Mentorship({
      startDate,
      files: fileId,
      className,
      description,
      isSuccessCase: isSuccessCase || 0
    })

    const savedClass = await newClass.save()
    await markFileAsReferenced(fileId)

    res.status(201).json({
      data: savedClass,
      message: '创建成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 获取所有班级
router.get('/queryClasses', async (req, res) => {
  try {
    const { year, classId, className, pageNum = 1, pageSize = 10 } = req.query
    const filter = {}
    const options = {
      skip: (pageNum - 1) * pageSize,
      limit: parseInt(pageSize),
      sort: { createdAt: -1 }
    }

    if (classId) {
      filter._id = classId
    }
    if (year) {
      filter.year = parseInt(year)
    }
    if (className) {
      // 模糊查询
      filter.className = { $regex: className, $options: 'i' }
    }

    const [classes, total] = await Promise.all([
      Mentorship.find(filter).populate('files').skip(options.skip).limit(options.limit).sort(options.sort),
      Mentorship.countDocuments(filter)
    ])

    res.json({
      data: classes,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / options.limit),
      total,
      message: '获取成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新班级
router.post('/updateClasses', authMiddleware(), async (req, res) => {
  try {
    const { fileId, classId, startDate, className, description, isSuccessCase } = req.body
    const cls = await Mentorship.findById(classId)
    if (!cls) return res.status(404).json({ message: '班级不存在' })

    // 处理图片更新
    if (fileId && fileId !== cls.files.toString()) {
      await unmarkFileReference(cls.files)
      await markFileAsReferenced(fileId)
      cls.files = fileId
    }

    // 如果更新了开始日期，则更新年份
    if (startDate) {
      // 将YYYY-MM-DD字符串转换为UTC时间
      const [year, month, day] = startDate.split('-')
      cls.year = new Date(Date.UTC(year, month - 1, day)).getUTCFullYear()
    }

    Object.assign(cls, { startDate, className, description, isSuccessCase })
    const updatedClass = await cls.save()

    res.json({
      data: updatedClass,
      message: '更新成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 删除班级
router.post('/deleteClasses', authMiddleware(), async (req, res) => {
  try {
    const { id } = req.body
    const cls = await Mentorship.findByIdAndDelete(id)
    if (!cls) return res.status(500).json({ message: '删除失败' })

    await unmarkFileReference(cls.files)

    res.json({ message: '班级已删除' })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

module.exports = router
